package com.lf.config;

import com.lf.base.PcObjectMapper;
import com.lf.interceptor.LocalInterceptor;
import com.lf.interceptor.SameUrlDataInterceptor;
import com.lf.interceptor.UrlPermissionInterceptor;
import com.lf.jwt.RepeatedlyReadFilter;
import com.lf.handler.EnumConverterFactory;
import com.lf.interceptor.TokenInterceptor;
import com.lf.jwt2admin.RepeatedlyReadForAdminFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;


/**
 * The class Mdc web mvc config.
 *
 */
@SuppressWarnings("unchecked")
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {


	/**
	 * 防止重复提交拦截器
	 */
	@Autowired
	private SameUrlDataInterceptor sameUrlDataInterceptor;

	@Autowired
	private TokenInterceptor tokenInterceptor;

	@Autowired
	private UrlPermissionInterceptor urlPermissionInterceptor;


	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(tokenInterceptor).addPathPatterns("/**")
				.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");

//		registry.addInterceptor(sameUrlDataInterceptor).addPathPatterns("/**");// 重复请求


		registry.addInterceptor(urlPermissionInterceptor).addPathPatterns("/admin/**","/customer/**")
				.excludePathPatterns("/admin/login", "/admin/addManager", "/admin/loginOut");//url资源权限判断

	}


    @Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverterFactory(new EnumConverterFactory());
	}
	/**
	 * 跨域支持
	 * @param registry
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				.allowedOrigins("*")
//				.allowedHeaders("*")
				.allowCredentials(true)
				.allowedMethods("GET", "POST", "DELETE", "PUT")
				.maxAge(3600 * 24);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("swagger-ui.html")
				.addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/");
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "E:/image/");
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		PcObjectMapper.buidMvcMessageConverter(converters);
	}

}
